//
//  BMSOnlineSessionManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSOnlineSessionManager.h"
#import <UIKit/UIKit.h>

#define kBMSOnlineDurationKey @"bms.totalOnlineSeconds"
#define kBMSLastLaunchTimestampKey @"bms.lastLaunchTime"

@interface BMSOnlineSessionManager ()
@property (nonatomic, assign) NSTimeInterval totalOnlineSeconds;
@property (nonatomic, assign) NSTimeInterval sessionStartTime;
@property (nonatomic, strong) NSTimer *tickTimer;
@end

@implementation BMSOnlineSessionManager

+ (instancetype)shared {
    static BMSOnlineSessionManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _totalOnlineSeconds = [[NSUserDefaults standardUserDefaults] doubleForKey:kBMSOnlineDurationKey];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(appDidEnterBackground)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(appWillEnterForeground)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
    }
    return self;
}

- (void)startTracking {
    self.sessionStartTime = [[NSDate date] timeIntervalSince1970];
    [self startTickTimer];
}

- (void)stopTracking {
    [self saveCurrentSessionDuration];
    [self stopTickTimer];
}

- (void)appDidEnterBackground {
    [self saveCurrentSessionDuration];
    [self stopTickTimer];
}

- (void)appWillEnterForeground {
    self.sessionStartTime = [[NSDate date] timeIntervalSince1970];
    [self startTickTimer];
}

- (void)saveCurrentSessionDuration {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval session = now - self.sessionStartTime;
    self.totalOnlineSeconds += session;
    [[NSUserDefaults standardUserDefaults] setDouble:self.totalOnlineSeconds forKey:kBMSOnlineDurationKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)startTickTimer {
    if (self.tickTimer) return;
    self.tickTimer = [NSTimer scheduledTimerWithTimeInterval:60
                                                       target:self
                                                     selector:@selector(tickTimerFired)
                                                     userInfo:nil
                                                      repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.tickTimer forMode:NSRunLoopCommonModes];
}

- (void)stopTickTimer {
    [self.tickTimer invalidate];
    self.tickTimer = nil;
}

- (void)tickTimerFired {
    if (self.onTickCheck) {
        self.onTickCheck(self.totalOnlineSeconds + [[NSDate date] timeIntervalSince1970] - self.sessionStartTime);
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

